package com.pjb.springbootjjwt.store.utils;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

public class RandomAccessFileUtil {

    /**
     * 换行符
     */
    public static final String sp = ";\r\n";

    /**
     * 空白填充
     */
    public static final char fill = 'V';

    /**
     * 删除一条记录：主键索引和表记录同时删除
     *
     * @param lineNo
     * @param lineSize
     * @param table
     */
    public static void delete(String table, long lineNo, int lineSize) throws Exception {
        RandomAccessFile raf = new RandomAccessFile(FileUtil.DIR + FileUtil.getPath(table), "rw");
        raf.seek(lineNo * (lineSize + 3));
        String c = StringUtil.over((byte) fill, lineSize);
        raf.write(c.getBytes(StandardCharsets.UTF_8));
        raf.close();
    }

    /**
     * 追加某件某一行的内容
     *
     * @param name
     * @param c
     */
    public static void append(String name, String c) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(FileUtil.DIR + FileUtil.getPath(name), "rw");
        raf.seek(raf.length());
        //raf.setLength(raf.length() + c.length());

        raf.write(c.getBytes(StandardCharsets.UTF_8));
        raf.close();
    }

    public static String get(String name, int index, int size) throws IOException {
        //获取内容
        RandomAccessFile raf = new RandomAccessFile(FileUtil.DIR + name, "r");
        raf.seek(index);
        byte[] bytes = new byte[size];
        raf.read(bytes);
        return new String(bytes, StandardCharsets.UTF_8);
    }

}
